package com.jesse.util;


import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;














import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.jesse.base.ManagerBase;
import com.jesse.custom.component.CustomDialog;
import com.jesse.custom.component.CustomWatitingDialog;
import com.jesse.custom.component.CustomWaveWatitingDialog;
import com.jesse.dao.ButtonDao;
import com.jesse.main.R;
import com.jesse.manager.PopupManager;
import com.romainpiel.titanic.library.Titanic;
import com.romainpiel.titanic.library.TitanicTextView;
import com.wang.avi.AVLoadingIndicatorView;

/**
 * 系统试图控制类，集合了页面跳转，弹窗，Toast提示， log提示功能。
 * 
 * @author jeissie 2014/5/26
 */
public class ViewUtil {
	//当前设备屏幕宽度
	private static int screenWidth = 480;
	//当前设备屏幕高度
	private static int screenHeight = 800;
	//等待弹窗
	private static Dialog waitingDialog = null; 
	//按键弹窗
	private static Dialog popup = null;
	//当前焦点Context
	private static Context context = null;
	//当前AppContext
	private static Context applicationContext = null;
	//当前入栈的Context
	private static List<Context> contexts;
	//输出时Log的Tag字符
	private static String TAG = "JOAF";
	//等待指示器的样式
	public static int indicatorType = -1;
	//等待指示器颜色
	public static int indicatorColor = -1;
	/**
	 * {@link ManagerBase}
	 * 
	 * 系统中Manager单例退出释放
	 */
	private static Map<String, ManagerBase> managerList;
	
	
	/**
	 * 设置Tag值，默认“JOAF”
	 * @param tAG
	 */
	public static void setTAG(String tAG) {
		TAG = tAG;
	}

	public static Context getApplicationContext() {
		return applicationContext;
	}

	public static void setApplicationContext(Context applicationContext) {
		ViewUtil.applicationContext = applicationContext;
	}

	public static Context getContext() {
		return context;
	}

	public static void setContext(Context context) {
		ViewUtil.context = context;
		if (contexts == null){
			contexts = new ArrayList<Context>();
		}
		contexts.add(context);
	}
	
	public static void setCurrentContext(Context context) {
		ViewUtil.context = context;
	}

	public static List<Context> getContexts() {
		return contexts;
	}
	
	public static void removeContext(Context context) {
		if (contexts == null) return;
		 Iterator<Context> iter = contexts.iterator();
		 while(iter.hasNext()){
			 Context c = (Context) iter.next();
			 if (c == context) {
				 c = null;
				 iter.remove();
			 }
			 if (ViewUtil.context == context) {
				 ViewUtil.context = null;
			 }
		 }
	}
	
	public static void init() {
		clearSystem();
		if (contexts == null){
			contexts = new ArrayList<Context>();
		} else {
			contexts.clear();
		}
		context = null;
		applicationContext = null;
	}

	public static void initWindowSize() {
		if (getApplicationContext() == null) return;
		DisplayMetrics metric = getApplicationContext().getResources().getDisplayMetrics();
		ViewUtil.setScreenWidth(metric.widthPixels);
		ViewUtil.setScreenHeight(metric.heightPixels);
	}
	
	public static void exitSystem() {
		clearSystem();
		finishAndClearContext();
		System.exit(0);
	}
	
	public static void finishAndClearContext() {
		int size = contexts.size();
		context = null;
		for (int i = 0; i < size ; i++) {
			Activity itemActivity = (Activity)contexts.get(i);
			if (itemActivity != null) {
				itemActivity.finish();
			}
		}
		contexts.clear();
		applicationContext = null;
	}
	
	public static void clearSystem() {
		closePopup();
		releaseAllManager();
	}
	
	public static void addManamger(String tag, ManagerBase manager) {
		if (managerList == null) {
			managerList = new HashMap<String, ManagerBase>();
		}
		managerList.put(tag, manager);
	}
	
	public static void releaseAllManager() {
		if (managerList == null) return;
		
		 Iterator iter = managerList.entrySet().iterator();
		 while(iter.hasNext()){
			 Map.Entry entry = (Map.Entry)iter.next();
			 ManagerBase item = (ManagerBase) entry.getValue();
			 if (item != null) {
				 item.releaseManager();
			 }
			 iter.remove();
		 }
		 managerList = null;
	}
	
	public static void exchangeActivity(Object object) {
		closePopup();
		Intent i = new Intent(context, (Class<?>) object);
		context.startActivity(i);
		((Activity) context).overridePendingTransition(R.anim.in_from_right, R.anim.out_alpha);
	}
	
	public static void exchangeActivity(Intent intent) {
		closePopup();
		context.startActivity(intent);
		((Activity) context).overridePendingTransition(R.anim.in_from_right, R.anim.out_alpha);
	}
	
	public static void exchangeActivityWithDefultAnimation(Object object) {
		closePopup();
		Intent i = new Intent(context, (Class<?>) object);
		context.startActivity(i);
	}
	
	public static void exchangeActivityWithDefultAnimation(Intent intent) {
		closePopup();
		context.startActivity(intent);
	}
	
	public static void exchangeAndFinishActivity(Intent intent) {
		Activity itemActivity = (Activity)contexts.get(contexts.size() - 1);
		exchangeAndFinishActivity(itemActivity, intent);
	}
	
	public static void exchangeAndFinishActivity(Object object) {
		Activity itemActivity = (Activity)contexts.get(contexts.size() - 1);
		exchangeAndFinishActivity(itemActivity, (Class<?>) object);
	}
	
	public static void exchangeAndFinishActivity(Activity activity, Intent intent) {
		closePopup();
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		((Activity) activity).overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
		activity.startActivity(intent);
		activity.finish();
	}
	
	public static void exchangeAndFinishActivity(Activity activity, Class startClass) {
		closePopup();
		Intent i = new Intent(activity, startClass);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		((Activity) activity).overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
		activity.startActivity(i);
		activity.finish();
	}
	
	public static void exchangeAndFinishAllActivity(Context context, Object object) {
		exitSystem();
		Intent i = new Intent(context, (Class<?>) object);
		context.startActivity(i);
		((Activity) context).overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
	}
	
	public static void finishActivityByCount(int count) {
		int size = contexts.size();
		count = count > size ? size : count;
		for (int i = size; i > size - count ; i--) {
			Activity itemActivity = (Activity)contexts.get(i - 1);
			if (itemActivity != null) {
				itemActivity.finish();
			}
		}
	}
	
	public static int getScreenWidth() {
		return screenWidth;
	}

	public static void setScreenWidth(int screenWidth) {
		ViewUtil.screenWidth = screenWidth;
	}
	
	public static int getScreenHeight() {
		return screenHeight;
	}

	public static void setScreenHeight(int screenHeight) {
		ViewUtil.screenHeight = screenHeight;
	}
	
	//对话框中间显示文字
	public static void popup(String content) {
		popopWithButton(content, null);
	}
	
	public static void popopWithButton(String content, ButtonDao button) {
		popupWithButton(content, applicationContext.getString(R.string.alert),  applicationContext.getString(R.string.confirm), button);
	}
	
	public static void popupWithButton(final String content, final String title, final String buttonName, final ButtonDao button) {
		Handler x = new Handler();
	       x.postDelayed(new Runnable() {
	           public void run() {
	        	   if (popup != null) {
		       			//TODO Popup should be a queue,and one by one be poped to fount.
		       			closePopup();
		       	   }
		       		CustomDialog.Builder builder = PopupManager.getInstance().popupWithButton(context, title, content, buttonName, button);
		       		builder.setCancelable(false); 
		       		popup = builder.create();
		       		popup.show();
	           }
       }, 300);
		
	}

	public static void popupWithTwoButton(String contentText, final ButtonDao positiveButton, final  ButtonDao negativeButton) {
		popupWithTwoButton(contentText, applicationContext.getString(R.string.alert), applicationContext.getString(R.string.confirm), positiveButton, 
				applicationContext.getString(R.string.cancel), negativeButton);
	}
	
	public static void popupWithTwoButton(String contentText, String title, String positiveButtonName, ButtonDao PositiveButton, 
			String negativeButtonName,  ButtonDao NegativeButton) {
		popupWithTwoButton(contentText, false, applicationContext.getString(R.string.alert), positiveButtonName, PositiveButton, negativeButtonName, NegativeButton);
	}
	
	public static void popupWithTwoButton(boolean isCancel, String contentText, String title, String positiveButtonName, ButtonDao PositiveButton, 
			String negativeButtonName,  ButtonDao NegativeButton) {
		popupWithTwoButton(contentText, isCancel, applicationContext.getString(R.string.alert), positiveButtonName, PositiveButton, negativeButtonName, NegativeButton);
	}
	
	public static void popupWithTwoButton(final String contentText, final boolean isCancel, final String title, final String positiveButtonName, final ButtonDao PositiveButton, 
			final String negativeButtonName, final  ButtonDao NegativeButton) {
		Handler x = new Handler();
	       x.postDelayed(new Runnable() {
	           public void run() {
	        	   if (popup != null) {
		       			//TODO Popup should be a queue,and one by one be poped to fount.
		       			closePopup();
		       		}
		       		CustomDialog.Builder builder = PopupManager.getInstance().popupWithTwoButton(context, title, contentText, 
		       				positiveButtonName, PositiveButton, negativeButtonName, NegativeButton);
		       		builder.setCancelable(isCancel); 
		       		popup = builder.create();
		       		popup.show();
	           }
	       }, 300);
	}
	
	
	
	//对话框中间显示图片
	public static void popupWihtImageAndButton (String title, int rid, ButtonDao button) {
		popupWihtImageAndButton(title, rid, applicationContext.getString(R.string.confirm), button);
	}
	
	public static void popupWihtImageAndButton(String title, int rid, String buttonName, ButtonDao button) {
		if (popup != null) {
			//TODO Popup should be a queue,and one by one be poped to fount.
			closePopup();
		}
		CustomDialog.Builder builder = PopupManager.getInstance().popupWithImageAndButton(context, rid, title, buttonName, button);
		builder.setCancelable(false); 
		popup = builder.create();
		popup.show();
	}
	
	public static void popupWihtImageAndButton (String title, int rid, ButtonDao positiveButton, ButtonDao negativeButton) {
		popupWihtImageAndButton(title, rid, applicationContext.getString(R.string.confirm), positiveButton, 
				applicationContext.getString(R.string.cancel), negativeButton);
	}
	
	public static void popupWihtImageAndButton (String title, int rid, String positiveButtonName, ButtonDao positiveButton, String negativeButtonName, ButtonDao negativeButton) {
		if (popup != null) {
			//TODO Popup should be a queue,and one by one be poped to fount.
			closePopup();
		}
		CustomDialog.Builder builder = PopupManager.getInstance().popupWithImageAndTwoButton(context, rid, title, positiveButtonName, positiveButton, 
				negativeButtonName, negativeButton);
		builder.setCancelable(false); 
		popup = builder.create();
		popup.show();
	}
	
	public static void popupWihtCustomViewAndButton (String title, View view, ButtonDao positiveButton, ButtonDao negativeButton) {
		popupWihtCustomViewAndButton(title, view, applicationContext.getString(R.string.confirm), positiveButton, 
				applicationContext.getString(R.string.cancel), negativeButton);
	}
	
	public static void popupWihtCustomViewAndButton (String title, View view, String positiveButtonName, ButtonDao positiveButton, String negativeButtonName, ButtonDao negativeButton) {
		if (popup != null) {
			//TODO Popup should be a queue,and one by one be poped to fount.
			closePopup();
		}
		CustomDialog.Builder builder = PopupManager.getInstance().popupWithCustomViewAndButton(context, view, title, positiveButtonName, positiveButton, 
				negativeButtonName, negativeButton);
		builder.setCancelable(false); 
		popup = builder.create();
		popup.show();
	}
	
	public static void popupWihtCustomViewWithoutButton (String title, View view) {
		if (popup != null) {
			//TODO Popup should be a queue,and one by one be poped to fount.
			closePopup();
		}
		CustomDialog.Builder builder = PopupManager.getInstance().createWithCustomViewWithoutButton(context, view, title);
		builder.setCancelable(true); 
		popup = builder.create();
		popup.show();
	}
	
	public static void closePopup() {
		if (popup == null)  return;
		popup.dismiss();
		popup = null;
	}
	
	public static Dialog getPopup() {
		return popup;
	}

	public static void setPopup(Dialog popup) {
		ViewUtil.popup = popup;
	}

	public static void Toast(int text) {
		Toast(text + "");
	}
	
	public static void Toast(float text) {
		Toast(text + "");
	}
	
	public static void Toast(String text) {
		if (context == null) {
			throw new NullPointerException("The activity context is null");
		}
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}
	
	public static void message(int text) {
		message("" + text);
	}
	
	public static void message(String text) {
		Log.v(TAG + " Message !!!", text);
	}
	
	public static void Error(int code) {
		Error(code + "");
	}
	
	public static void Error(String text) {
		Log.v(TAG + " Error !!!", text);
	}
	
	public static void Debug(int code) {
		Debug(code + "");
	}
	
	public static void Debug(String text) {
		if (!AppUtil.DEBUG) return;
		System.out.println(TAG + " Debug !!! " + text);
	}
	
	public static void waiting() {
		waiting("");
	}
	
	public static void waiting(boolean canBeCancel) {
		waiting("", canBeCancel);
	}
	
	public static void waiting(String text) {
		waiting(text, false);
	}
	
	public static void waiting(String text, boolean canBeCancel) {
		if (context == null) return;
		if (waitingDialog != null) {
			endWaiting();
		}
		if (text.isEmpty()) {
			text = applicationContext.getString(R.string.pleaseWaiting);
		}
		if (indicatorType == -1) {
			indicatorType = AVLoadingIndicatorView.BallClipRotateMultiple;
		}
		if (indicatorColor == -1) {
			indicatorColor = getContext().getResources().getColor(R.color.blue);
		}
		waitingDialog = new CustomWatitingDialog(context, text, indicatorType, indicatorColor, canBeCancel);
		waitingDialog.show();
		waitingDialog.setCancelable(canBeCancel);
		waitingDialog.setCanceledOnTouchOutside(false);
	}
	
	public static void waiting(Dialog dialog) {
		if (waitingDialog != null) {
			endWaiting();
		}
		waitingDialog = dialog;
		waitingDialog.show();
	}
	
	public static Dialog getWaiting() {
        return waitingDialog;
	}
	
	public static void endWaiting() {
		if (waitingDialog == null) return;
		waitingDialog.dismiss();
		waitingDialog = null;
	}
	
	public static Dialog getWaitingDialog() {
		return waitingDialog;
	}

	public static void setWaitingDialog(Dialog waitingDialog) {
		ViewUtil.waitingDialog = waitingDialog;
	}
	
	public static void waveWaiting() {
		waveWaiting("");
	}
	
	public static void waveWaiting(boolean canBeCancel) {
		waveWaiting("", canBeCancel);
	}
	
	public static void waveWaiting(String text) {
		waveWaiting(text, false);
	}
	
	public static void waveWaiting(String text, boolean canBeCancel) {
		if (waitingDialog != null) {
			endWaiting();
		}
		if (text.isEmpty()) {
			text = applicationContext.getString(R.string.pleaseWaiting);
		}

		waitingDialog = new CustomWaveWatitingDialog(context, text, canBeCancel);
		waitingDialog.show();
	}
	
	public static void hideKeyBoard() {
		if (context == null) return;
		InputMethodManager inputmanger = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		if(((Activity) context).getWindow().peekDecorView() != null && inputmanger != null) 
			inputmanger.hideSoftInputFromWindow(((Activity) context).getWindow().peekDecorView().getWindowToken(), 0);	
	}
	
	public static void showKeyBoard() {
		if (context == null) return;
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);  
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
	}
	/**
  	 * 通过View试图生成BitMap
  	 * 
  	 * @param view 任何view或其的子类均可
  	 * @return
  	 */
  	public static Bitmap convertViewToBitmap(View view){
  		 if (view == null) {  
             return null;  
         }  
         Bitmap screenshot;  
    	 screenshot = Bitmap.createBitmap(view.getWidth() , view.getMeasuredHeight(), Config.RGB_565);
         Canvas c = new Canvas(screenshot);  
         c.translate(-view.getScrollX(), -view.getScrollY()); 
         view.draw(c);  
         return screenshot;  
  	}
}
